const mongoose = require('mongoose');
const crypto = require('crypto');
const xss = require('xss');
const _ = require('lodash');
const User = require('../models/user');
const Message = require('../models/message');
const Group =require('../models/group');
const Socket = require('../models/socket');
const { getJwt, testJwt } = require('../utils');

const messageCount = 20;
// 获取聊天信息列表
exports.list = async (ctx, next) => {
    const { id } = ctx.request.query;
    
    await new Promise(async (resolve, reject) => {
        User.findOne({_id: id}, function(err, data) {
            let name;
            if (err) {
                reject(err);
            } else if (data) {
                name = data.name;
            }
            Message.find({'$or': [{ to: id }, { from: id }]}, function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    resolve({data, name: name});
                }
            })
        })
        
    }).then(data => {
        ctx.body = {
            reasonCode: 200,
            ...data
        }
    }).catch(err => {
        ctx.body = err;
    })
    
}


exports.linkmansLastMessage = async (ctx, next) => {

    const { linkmansId } = ctx.request.query;
    const linkmans = linkmansId.split(',');
    const promises = linkmans.map(linkmanId => {
        const isGroup = linkmanId.indexOf('_') === -1;
        
        if (!isGroup) { // 个人聊天
            return Message
            .find(
                { id: linkmanId }, 
                { content: 1, to: 1, from: 1, create_time: 1, toWho: 1, id: 1 }, 
                { limit: messageCount, sort: { create_time: -1 } }
            )
            .populate('from to', { avatar: 1, name: 1 })
        } else { // 群组聊天
            return Message
            .find(
                { id: linkmanId }, 
                { content: 1, to: 1, from: 1, create_time: 1, toWho: 1, id: 1 }, 
                { limit: messageCount, sort: { create_time: -1 } }
            )
            .populate('from', { avatar: 1, name: 1 }).populate('to', { name: 1, avatar: 1 }, Group)
        }
    });
    const results = await Promise.all(promises);
    const messages = {};
    linkmans.forEach((linkmanId, index) => {
        if (results[index].length) {
            messages[linkmanId] = results[index];
        }
    })
    ctx.body = {
        reasonCode: 200,
        messages
    }
}

exports.linkmanHistoryMessage = async (ctx, next) => {
    const { existCount, id } = ctx.request.query;
    const isGroup = id.indexOf('_') === -1;
    let messages = [];
    if (isGroup) {
        messages = await Message
                        .find(
                            { id }, 
                            { content: 1, to: 1, from: 1, create_time: 1, toWho: 1, id: 1 }, 
                            { limit: messageCount + parseInt(existCount), sort: { create_time: -1 } }
                        )
                        .populate('from', { name: 1, avatar: 1 }).populate('to', { name: 1, avatar: 1 }, Group);
    } else {
        messages = await Message
                        .find(
                            { id }, 
                            { content: 1, to: 1, from: 1, create_time: 1, toWho: 1, id: 1 }, 
                            { limit: messageCount + parseInt(existCount), sort: { create_time: -1 } }
                        )
                        .populate('from to', { name: 1, avatar: 1 })
    }
    
    ctx.body = {
        reasonCode: 200,
        messages
    }
}
